package util

import (
	"fileNest/config"
	"fileNest/model"
	"strings"
	"time"

	"github.com/golang-jwt/jwt"
	"golang.org/x/crypto/bcrypt"
)

// 获取 secret
func GetSecret() string {
	if config.AppConfig != nil {
		return config.AppConfig.App.Secret
	}
	return "defaultSecretKey"
}

// 生成hash密码
func HashPassword(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
	return string(hash), err
}

// 生成 JWT
func GenerateJWT(user model.UserInfo) (stringToken string, err error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"userId": user.Id,
		"exp":    time.Now().Add(time.Hour * 24 * 7).Unix(),
	})
	stringToken, err = token.SignedString([]byte(GetSecret()))
	stringToken = "Bearer " + stringToken
	return
}

// 校验密码
func CheckPassWorkHash(hash, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

// 解析 JWT
func ParseJWT(tokenString string) (token *jwt.Token, userID string, err error) {
	tokenString = strings.TrimPrefix(tokenString, "Bearer ")
	token, err = jwt.Parse(tokenString, func(tokenString *jwt.Token) (interface{}, error) {
		return []byte(GetSecret()), nil
	})
	if err != nil || !token.Valid {
		return
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	userID, ok = claims["userId"].(string)
	if !ok {
		return
	}
	return
}
